<template>
  <div>
    <!-- <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="'/home'">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb> -->
    <MBX Biao='用户管理' Biao1='用户列表'></MBX>
    <!-- 卡片 -->
    <!--clearable   input框出现一个小叉叉，清空当前输入框里的内容  -->
    <!-- clear   清空事件  点击由clearable属性生成的按钮清空 -->
    <!-- input 在Input值改变时触发 相当于监听  边搜索边体现搜索效果 -->
    <el-card class="mt">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="tableData.query"
            class="input-with-select"
            
            clearable
            @clear='sou'
            @input='sou'
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="sou"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="14">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <template>
        <el-table :data="userlist" class="mt" border style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="address" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="tai(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="edit(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="del(scope.row.id)"
              ></el-button>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click='setUser(scope.row)'></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!--  -->

      <!-- 分页 -->
      <div class="mt">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="tableData.pagenum"
          :page-sizes="[3, 6, 9]"
          :page-size="tableData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加弹出框 -->

    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width='45%'>
      <el-form :model="form" :rules="rules" ref='formTj'>
        <el-form-item label="用户" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>
    <!--  -->

    <!-- 编辑弹框 -->
    <el-dialog title="编辑用户" :visible.sync="dialogVisiblebj" width='50%'>
      <el-form :model="edito" :rules="rulesbj" ref='formBj'>
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="edito.username" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="edito.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="edito.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addbj">确 定</el-button>
      </div>
    </el-dialog>
    <!--  -->

    <!-- 角色分配 -->
    <el-dialog
  title="角色分配"
  :visible.sync="dialogVisible"
  width="40%"
  >
  <div>
    <p>当前用户：<span>{{currentUser.username}}</span></p>
    <p>当前角色：<span>{{currentUser.role_name}}</span></p>
    <span  class="mr">分配角色---{{zscUser.id}}</span>
    <el-select v-model="zscUser.id" placeholder="请选择">
    <el-option
      v-for="item in zscUser"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </div>
  
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!--  -->
  </div>
</template>

<script>
import { Listuser, zTai,zscJs,zscJslist } from "@/http/api";
import { addUser } from "@/http/api";
import { delUser } from "@/http/api";
import { eDit } from "@/http/api";
import _ from 'lodash';

export default {
  data() {
    //验证邮箱的方法
    const checkEmail = (rule, value, callback) => {
      //邮箱正则
      const zzEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (!zzEmail.test(value)) {
        return callback(new Error("你的邮箱正则不正确，请检查并重新输入"));
      }
      callback();
    };

    //手机号验证方法
    const eMobile = (rule, value, callback) => {
      //手机号正则
      const zzMobile = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!zzMobile.test(value)) {
        return callback(new Error("你的手机号正则不正确，请检查并重新输入"));
      }
      callback();
    };

    return {
      //当前用户id
      jsRoleId:"",
      value:"",
      jsList:[],//角色分配的数组
      currentUser:{},//当前用户对象
      zscUser:[],
      dialogVisible: false, //分配角色变量
      tableData: {
        query: "",
        pagenum: 1, //页数
        pagesize: 3,//每页条数
      },
      userlist: [],
      total: 0,
      dialogFormVisible: false,
      dialogVisiblebj: false,
      //添加的对象
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },

      formLabelWidth: "70px",
      //添加
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" },
        ],
        email: [
          {required: true, validator: checkEmail, trigger: "blur" },
          // { required: true, message: '请输入邮箱号', trigger: 'blur' },
          // { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: eMobile, trigger: "blur" },
          // { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
        ],
      },
      //编辑的对象
      edito: {
        id: "",
        username:'',
        email: "",
        mobile: "",
      },
      zt: {
        uId: "",
        mg_state: false,
      },
      //编辑
      rulesbj: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        // email: [{ required: true, message: "请输入邮箱号", trigger: "blur" }],
         email: [
          {required: true, validator: checkEmail, trigger: "blur" },
          // { required: true, message: '请输入邮箱号', trigger: 'blur' },
          // { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        // mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: eMobile, trigger: "blur" },
          // { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
        ],
      },
    

    };
  },
  created() {
    this.getList();
  },
  methods: {
    async addUser(){
       const res=await zscJslist(this.jsRoleId,this.zscUser.id)
       console.log(res);
       this.getList();
        this.dialogVisible=false;
    },
    // //打开分配角色的弹框
   async setUser(row){
      this.dialogVisible=true;
      console.log('打开用户信息',row);
    
      //结构获取用户名和角色名
      const{id,username,role_name}=row
      this.jsRoleId=id
      console.log(this.jsRoleId);
      //将用户名和角色名赋值给当前用户对象
      this.currentUser={username,role_name}
      //获取所有可能的角色列表接口
      const res=await zscJs()

      this.zscUser=res

      console.log(13212,res);
      this.getList();
    },
    //搜索
    sou:_.debounce(function(){
       this.getList();
    },300),
     //开关状态
    async tai(row) {
      //  console.log(row)
      this.zt.uId = row.id;
      this.zt.mg_state = row.mg_state;
      const res = await zTai(this.zt);
      console.log(res);
    },
    //删除单个数据
    async del(id) {
      const res=await this.$confirm('你敢删我, 嗯?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '已取消删除'
          });          
        })

        if(res==='confirm'){
          //调用封装的删除接口
          await delUser(id);
          console.log("删除单个数据", res);
          this.getList();
        }



      
    },
   
    //编辑用户,先获取数据
    edit(row) {
   console.log(row);
      this.dialogVisiblebj = true;
      this.id = row.id;
      const {username,email,mobile}=row;
      this.edito= {username,email,mobile}
      console.log(this.edito);
      // this.edito.username = row.username;
      // this.edito.email = row.email;
      // this.edito.mobile = row.mobile;
      
    },
     //编辑用户并提交
   addbj() {

        // this.$refs.formTj.validate(async (valid) => {
        // if (!valid) return;
        // const res = await addUser(this.form);
        // console.log("添加用户", res);
        // this.dialogFormVisible = false;
        // this.getList();
      this.$refs.formBj.validate(async(valid)=>{
        if(!valid) return;
        const {username,email,mobile}=this.edito
        const res = await eDit(this.id,{username,email,mobile});
        console.log("编辑用户", res);
        
        this.dialogVisiblebj = false;
        this.getList();
      })

    },
    //添加用户
    add() {
      //       obj= {
      //   username: this.form.username,
      //   password: this.form.password,
      //   email: this.form.email,
      //   mobile: this.form.mobile,
      // }
      this.$refs.formTj.validate(async (valid) => {
      if (!valid) return;
        // for(let index=0;index<10;index++){
          // this.form.username+=1
          // this.form.password+=1
        const res = await addUser(this.form);
        console.log("添加用户", res);
        this.dialogFormVisible = false;
        this.getList();
        // }
      });
      this.form.username = "";
      this.form.password = "";
      this.form.email = "";
      this.form.mobile = "";
    },
    //调用用户列表数据
    async getList() {
      const res = await Listuser(this.tableData);
      console.log("用户列表数据", res);
      let { total, users } = res;
      this.userlist = users;
      this.total = total;
    },
    //分页
    handleSizeChange(val) {
      this.tableData.pagesize = val;
      this.getList();
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.tableData.pagenum = val;
      this.getList();
      // console.log(`当前页: ${val}`);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-row {
  text-align: left;
}
</style>
